package ch01Exercise;

public class IString {
    Charary tail = new Charary();
    Charary rear = tail;

    public IString(String x) {
        char[] a = x.toCharArray();
        for (int i = 0; i < a.length; i++) {
            rear.next = new Charary(a[i]);
            rear = rear.next;
        }
    }
    public IString(IString x) {
        for (Charary p = x.tail.next; p != x.rear.next; p = p.next) {
            rear.next = new Charary(p.oneChar);
            rear = rear.next;
        }
    }
    public IString() {
        this("");
    }
    public void clearall() {
        this.tail.next = null;
    }
    public char charAt(int index) {
        Charary p = this.tail;
        while (index != 0 && p.next != null) {
            p = p.next;
            index--;
        }
        if(p==null){
            return 'N';
        }
        return p.oneChar;
    }

    public void pus() {
        for (Charary p = tail.next; p != rear.next; p = p.next) {
            System.out.print(p.oneChar);
        }
        System.out.println();
    }


    public boolean addAt(int index, IString X) {
        Charary p = this.tail;
        boolean flag = false;
        while(index>1){
            p=p.next;
            index--;
        }
        if(p!=null){
            flag=true;
            X.rear.next=p.next;
            p.next=X.tail.next;
        }
        if(rear.next!=null){
            rear=X.rear;
        }
        return flag;
    }

    public String toString(){
        String a = "";
        for(Charary p=tail.next;p!=rear.next;p=p.next){
            a=a+p.oneChar;
        }
        return a;
    }

}